import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/user.dart';

class AuthService {
  // 使用相对路径，这样请求会发送到提供静态页面的同一服务器
  static const String _baseUrl = '/api/v1';

  // 用户登录
  Future<User> login(String username, String password) async {
    try {
      final response = await http.post(
        Uri.parse('$_baseUrl/auth/login'),
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode({
          'username': username,
          'password': password,
        }),
      );

      final Map<String, dynamic> responseBody = jsonDecode(response.body);
      
      if (response.statusCode == 200 && responseBody['code'] == 0) {
        final Map<String, dynamic> data = responseBody['data'];
        return User.fromJson(data);
      } else {
        throw Exception(responseBody['message'] ?? '登录失败');
      }
    } catch (e) {
      throw Exception('登录失败: ${e.toString()}');
    }
  }

  // 用户注册
  Future<User> register(String username, String email, String password) async {
    try {
      final response = await http.post(
        Uri.parse('$_baseUrl/auth/register'),
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode({
          'username': username,
          'email': email,
          'password': password,
        }),
      );

      final Map<String, dynamic> responseBody = jsonDecode(response.body);
      
      if (response.statusCode == 201 && responseBody['code'] == 0) {
        final Map<String, dynamic> data = responseBody['data'];
        return User.fromJson(data);
      } else {
        throw Exception(responseBody['message'] ?? '注册失败');
      }
    } catch (e) {
      throw Exception('注册失败: ${e.toString()}');
    }
  }

  // 验证token
  Future<bool> validateToken(String token) async {
    try {
      final response = await http.get(
        Uri.parse('$_baseUrl/auth/validate'),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer $token',
        },
      );

      final Map<String, dynamic> responseBody = jsonDecode(response.body);
      return response.statusCode == 200 && responseBody['code'] == 0;
    } catch (e) {
      return false;
    }
  }

  // 更新用户信息
  Future<User> updateProfile(String token, Map<String, dynamic> data) async {
    try {
      final response = await http.put(
        Uri.parse('$_baseUrl/auth/profile'),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer $token',
        },
        body: jsonEncode(data),
      );

      final Map<String, dynamic> responseBody = jsonDecode(response.body);
      
      if (response.statusCode == 200 && responseBody['code'] == 0) {
        final Map<String, dynamic> userData = responseBody['data'];
        return User.fromJson(userData);
      } else {
        throw Exception(responseBody['message'] ?? '更新个人信息失败');
      }
    } catch (e) {
      throw Exception('更新个人信息失败: ${e.toString()}');
    }
  }

  // 修改密码
  Future<void> changePassword(
    String token,
    String currentPassword,
    String newPassword,
  ) async {
    try {
      final response = await http.put(
        Uri.parse('$_baseUrl/auth/password'),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer $token',
        },
        body: jsonEncode({
          'currentPassword': currentPassword,
          'newPassword': newPassword,
        }),
      );

      final Map<String, dynamic> responseBody = jsonDecode(response.body);
      
      if (response.statusCode != 200 || responseBody['code'] != 0) {
        throw Exception(responseBody['message'] ?? '修改密码失败');
      }
    } catch (e) {
      throw Exception('修改密码失败: ${e.toString()}');
    }
  }
}